<template>
  <div class="app-container">
    <h2 style="text-align: center;">选择试题</h2>
    <el-steps :active="2" process-status="wait" align-center style="margin-bottom: 40px;">
      <el-step title="填写基本信息" />
      <el-step title="创建试题" />
      <el-step title="最终审核" />
    </el-steps>

    <!-- 主体 -->
    <el-row class="jt-do" :gutter="10">
      <el-col class="jt-do__left" :xs="9" :sm="7" :md="5" :lg="4" :xl="2">
        <!-- 左侧的总得分框 -->
        <div class="jt-small_tip3" v-for="(item,index) in shiti " :key="index">
          <div class="jt-small_tip3__left">
            <h3>
              <span>{{index+1 }}.</span>
              {{item.type | shitiType}}
            </h3>
            <p>
              每题分数
              <el-input v-model="item.score"></el-input>分
            </p>
            <p>
              <span>{{shiti[index] | shitiFind}}</span>
            </p>
          </div>
        </div>

        <div class="jt-total" v-if="shiti.length>0">
          <p>
            总题数：
            <span>{{totalNum}}</span>题
          </p>
          <p>
            当前总分：
            <span>{{totalScore}}</span>分
          </p>
        </div>
      </el-col>
      <!-- do右边 -->
      <el-col class="jt-do__right" :xs="15" :sm="17" :md="19" :lg="20" :xl="22">
        <div class="jt-list4_2">
          <!-- 单选题 -->
          <div class="jt-list4_2__main" v-for="(item,index) in shiti " :key="index">
            <div class="jt-list4_2__main__title">
              <div class="jt-list4_2__main__title__header">
                <span>{{index+1 | NoToChinese}}，</span>
                <span>
                  {{item.type | shitiType}}(共 {{item.data.length}}题，每小题 {{item.score}} 分，合计{{item.data.length*item.score}}分
                  )
                </span>
              </div>
              <div class="jt-small_tip2__setting--top">
                <el-tooltip effect="dark" content="移除" placement="top">
                  <a @click="ShitiType(0,item.type)">
                    <i class="el-icon-delete"></i>
                  </a>
                </el-tooltip>
                <el-tooltip effect="dark" content="下移" placement="top">
                  <a @click="ShitiType(1,item.type)">
                    <i class="el-icon-bottom"></i>
                  </a>
                </el-tooltip>
                <el-tooltip effect="dark" content="上移" placement="top">
                  <a @click="ShitiType(2,item.type)">
                    <i class="el-icon-top"></i>
                  </a>
                </el-tooltip>
              </div>
            </div>
            <div class="jt-list4_2__main-item" v-for="(i,j) in item.data" :key="j">
              <div class="jt-do__right__left">
                <div class="jt-list4_2__main__content">
                  <div class="jt-list4_2__main__content__header">
                    <span>{{j+1}}.</span>
                  </div>
                  <div v-html="i.title"></div>
                  <div class="jt-list4_2__main__content__footer">
                    <el-radio-group v-for="(m,n) in i.questionMap" :key="n">
                      <el-radio v-for="(b,q) in m" :key="q">{{b}}</el-radio>
                    </el-radio-group>
                    <p>
                      答案
                      <span>{{i.isAnswer}}</span>
                    </p>

                    <p v-if="item.type==97">
                      是否正确
                      <span>{{i.flag | sexs}}</span>
                    </p>
                    <p>
                      解析：
                      <span v-html="i.analysis"></span>
                    </p>
                  </div>
                </div>
              </div>
              <div class="jt-small_tip2 jt-do__right__right">
                <div class="jt-small_tip2__setting--top">
                  <el-tag>{{i.difficultyName}}</el-tag>
                  <el-tooltip effect="dark" content="移除" placement="top">
                    <a @click="QuestionType(0,i.id,j,index)">
                      <i class="el-icon-delete"></i>
                    </a>
                  </el-tooltip>
                  <el-tooltip effect="dark" content="下移" placement="top">
                    <a @click="QuestionType(1,i.id,j,index)">
                      <i class="el-icon-bottom"></i>
                    </a>
                  </el-tooltip>
                  <el-tooltip effect="dark" content="上移" placement="top">
                    <a @click="QuestionType(2,i.id,j,index)">
                      <i class="el-icon-top"></i>
                    </a>
                  </el-tooltip>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="jt-addquestion">
          <div class="create_q_contain" v-if="addquestion" @click="show()">
            <i class="el-icon-circle-plus-outline"></i>
            <span>创建新的大题</span>
          </div>
          <div class="create_q_contain" v-else @click.self="show()">
            <el-row>
              <el-button type="primary" @click="addType(95)">选择题</el-button>

              <el-button type="primary" @click="addType(96)">判断题</el-button>
              <el-button type="primary" @click="addType(97)">填空题</el-button>
              <el-button type="primary" @click="addType(100)">简答题</el-button>
            </el-row>
          </div>
        </div>
        <div class="footer">
          <el-button type="primary" @click="goback">上一步</el-button>
          <el-button type="primary">保存草稿</el-button>
          <el-button type="primary" @click="saveOrUpdate">下一步</el-button>
        </div>
      </el-col>
    </el-row>

    <shitipupup ref="addOrUpdate" @refreshDataList="getData"></shitipupup>
  </div>
</template>
<script>
import shitipupup from "@/views/modules/tiku/shitipupup";

export default {
  data() {
    return {
      flag: false,
      saveBtnDisabled: false, // 保存按钮是否禁用
      addquestion: true,
      paperId: null,
      datalist: [],
      shiti: [
        // {
        // type: "选择",
        // score: 5,
        // data: [
        // {
        //   id: 1001,
        //   type: 95,
        //   difficultyName: "一般",
        //   title: "<p>\n\t关于电子商务，以下哪种说法是错误的（）。</p>",
        //   kword: "，网络规划设计师第012套，网络规划设计师第012套",
        //   isAnswer: "D",
        //   questionDelHTMLTag:
        //     '[{"A":"电子商务可以使用户方便的进行网上购物","B":"电子商务可以使用户方便的进行网上交易","C":"电子商务可以使用户方便的进行网上支付","D":"电子商务活动要求用户利用PC机上网完成"}]',
        //   analysis:
        //     "<p>\n\t电子商务可以使用户方便的进行网上购物，电子商务可以使用户方便的进行网上交易。电子商务可以使用户方便的进行网上支付。</p>",
        //   questionMap: [
        //     {
        //       a: "电子商务可以使用户方便的进行网上购物",
        //       b: "电子商务可以使用户方便的进行网上交易",
        //       c: "电子商务可以使用户方便的进行网上支付",
        //       d: "电子商务活动要求用户利用PC机上网完成",
        //     },
        //   ],
        // },
        //   ],
        // },
      ],
    };
  },

  components: {
    shitipupup: shitipupup,
  },
  computed: {
    totalNum: function () {
      let num = 0;
      if (this.shiti.length > 0) {
        this.shiti.forEach((item) => {
          num += item.data.length;
        });
      }
      return num;
    },

    mainTabs: {
      get() {
        return this.$store.state.common.mainTabs;
      },
      set(val) {
        this.$store.commit("common/updateMainTabs", val);
      },
    },

    totalScore() {
      let num = 0;
      if (this.shiti.length > 0) {
        this.shiti.forEach((item) => {
          num += item.data.length * item.score;
        });
      }
      return num;
    },
  },

  created() {
    if (this.$route.params && this.$route.query.id) {
      this.paperId = this.$route.query.id;
    } else {
      this.paperId = 0;
    }
  },
  watch: {
    paperId(newName, oldName) {
      console.log(oldName);
      console.log(newName);
      if(newName == 0)
      {
        console.log("a");
         this.$router.push({
        path: "/tiku-activity?" 
      });
      }
    },
  },
  methods: {
    saveOrUpdate() {
      // this.$router.push({
      //   path: "/tiku-end?id=" + 1,
      // });
      let newData = [];
      if (this.totalScore == 0) {
        console.log("呵呵");
      } else {
        this.shiti.forEach((item) => {
          let questionIDs = [];

          item.data.forEach((j) => {
            questionIDs.push(j.id);
          });

          newData.push({
            paperId: this.paperId,
            score: item.score,
            questionIds: questionIDs,
          });
        });
        console.log(newData);

        this.$http({
          url: this.$http.adornUrl(`/tiku/paperquestion/save`),
          method: "post",
          data: this.$http.adornData(newData, false),
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message({
              message: "操作成功",
              type: "success",
              duration: 1500,
              onClose: () => {
                this.$router.push({
                  path: "/tiku-end?id=" + this.paperId,
                });
              },
            });
          } else {
            this.$message.error(data.msg);
          }
        });
      }
    },
  /**
   * 切换试题顺序
   */
    ShitiType(type, id) {
      console.log(type);
      console.log(id);
    },

    QuestionType(type, id, j, index) {
      if (type == 0) {
        this.$confirm(`此操作将删除第  ${j + 1} 号元素, 是否继续?`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            if (this.shiti[index].data.length == 1) {
              this.shiti.splice(index, 1);
            } else {
              this.shiti[index].data.splice(j, 1);
            }

            this.$message({
              type: "success",
              message: "删除成功!",
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
      }
      if (type == 1 || type == 2) {
        if (this.shiti[index].data.length == 1) {
          this.$message({
            message: `只有一个，不能[${type == 1 ? "向下" : "向上"}]移动啦`,
            type: "warning",
          });
        }
        if (j == 0 && type == 2) {
          this.$message({
            message: `头部元素不能向上移动啦`,
            type: "warning",
          });
        }

        if (j != 0 && type == 2) {
          var tempOption = this.shiti[index].data[j - 1];

          this.$set(this.shiti[index].data, j - 1, this.shiti[index].data[j]);
          this.$set(this.shiti[index].data, j, tempOption);
        }
        if (j == this.shiti[index].data.length - 1 && type == 1) {
          this.$message({
            message: `尾部元素不能向下移动啦`,
            type: "warning",
          });
        }
        if (j != this.shiti[index].data.length - 1 && type == 1) {
          var tempOption = this.shiti[index].data[j + 1];
          this.$set(this.shiti[index].data, j + 1, this.shiti[index].data[j]);
          this.$set(this.shiti[index].data, j, tempOption);
        }
      }
    },
    getData(data) {
      this.$nextTick(() => {
        this.datalist = data;
        console.log(this.datalist);

        if (this.shiti.length > 0) {
          let index = this.shiti.findIndex((item) => {
            return item.type == this.datalist[0].type;
          });

          if (index == -1) {
            this.shiti.push({
              data: this.datalist,
              score: 0,
              type: this.datalist[0].type,
            });
          } else {
            this.shiti[index].data = this.hebing(
              this.shiti[index].data,
              this.datalist
            );
            this.shiti[index].data = this.unique(this.shiti[index].data, "id");
          }
        } else {
          this.shiti.push({
            data: this.datalist,
            score: 0,
            type: this.datalist[0].type,
          });
        }
      });
    },
    unique(arr, field) {
      var map = {};
      var res = [];
      for (var i = 0; i < arr.length; i++) {
        if (!map[arr[i][field]]) {
          map[arr[i][field]] = 1;
          res.push(arr[i]);
        }
      }
      return res;
    },

    hebing(arr1, arr2) {
      for (var i = 0; i < arr1.length; i++) {
        for (var j = 0; j < arr2.length; j++) {
          if (arr1[i] === arr2[j]) {
            arr1.splice(i, 1); //利用splice函数删除元素，从第i个位置，截取长度为1的元素
          }
        }
      }
      //alert(arr1.length)
      for (var i = 0; i < arr2.length; i++) {
        arr1.push(arr2[i]);
      }
      return arr1;
    },

    goback() {
      this.$router.push({
        path: "/tiku-activity?id=" + 1,
      });
    },
    show() {
      this.addquestion = !this.addquestion;
    },
    addType(type) {
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(type);
      });
    },
  },
};
</script>
